package com.jfinal.aceadmin.controller;

import java.util.Date;

import com.jfinal.aceadmin.model.User;
import com.jfinal.aceadmin.model.UserImpl;
import com.jfinal.aceadmin.util.ConstantKit;
import com.jfinal.aceadmin.util.DateUtil;
import com.jfinal.aceadmin.util.DesUtil;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;

@ControllerBind(controllerKey = "/admin/user", viewPath = "/admin/")
public class UserController extends Controller {

	public void login() {
		render("more_pages/login.html");
	}
	
	public void logout() {
		removeSessionAttr("name");
		removeSessionAttr("icon");
		redirect("/admin/user/login");
	}

	public void doLogin(){
		String emailAddress = getPara("emailAddress");
		String password = getPara("password");
		User user = UserImpl.getDAO().login(emailAddress,password);
		String name = user.getStr("name");
		String icon = user.getStr("icon");
		setSessionAttr("name", name);
		String server = PropKit.use("server_config.properties").get(
				"serverAddress",ConstantKit.DEFAULT_SERVER);
		String iconUrl = getRequest().getScheme() + "://" + server
				+ "/icon/" + icon;
		setSessionAttr("iconUrl", iconUrl);
		redirect("/admin");
	}
	
	public void register() {
		String emailAddress = getPara("emailAddress");
		String name = getPara("name");
		String password = getPara("password");
		String rePass = getPara("rePassword");
		String icon = getPara("icon");
		String birthday = getPara("birthday");
		boolean result = UserImpl.getDAO().validateUser(emailAddress,name,password,birthday);
		if (rePass.equals(password) && result) {
			String newPass = DesUtil.encrypt(password, emailAddress);
			User user = new User();
			user.setEmailAddress(emailAddress);
			user.setPassword(newPass);
			user.setName(name);
			user.setIcon(icon);
			user.setCreatedDate(new Date());
			user.setLastLoginDate(new Date());
			user.setBirthday(DateUtil.parseDate(birthday));
			int age = DateUtil.getYearsBeforeNow(user.getBirthday());
			user.setAge(age);
			user.save();
			setSessionAttr("name", name);
			String server = PropKit.use("server_config.properties").get(
					"serverAddress",ConstantKit.DEFAULT_SERVER);
			String iconUrl = getRequest().getScheme() + "://" + server
					+ "/icon/" + icon;
			setSessionAttr("iconUrl", iconUrl);
		}
		redirect("/admin");
	}

}
